from datetime import datetime, timedelta
import pytz

import coin.exchange.base.kr_rest.public_client_base as pubcb
import coin.exchange.dydx_futures.kr_rest.native_public_client as npubc
from coin.exchange.kr_rest.product.product_impl import generate_product_from_str2
from coin.proto.coin_market_query_pb2 import (
    ProductKline,
    ProductKlineElement)


class DydxFuturesFeedParser(object):
  @staticmethod
  def parse_native_kline(update_msg, product, kline_period):
    klines = update_msg
    kline_group = []
    for kline in klines['candles']:
      dt = datetime.strptime(kline['startedAt'].split('.')[0], '%Y-%m-%dT%H:%M:%S')
      product_kline = ProductKlineElement(
          kline_timestamp=int(dt.timestamp() * 10**9),
          open=float(kline['open']),
          high=float(kline['high']),
          low=float(kline['low']),
          close=float(kline['close']),
          volume=float(kline['baseTokenVolume']),
          turnover=float(kline['usdVolume'])
      )
      kline_group.append(product_kline)
    return ProductKline(
        symbol=product.symbol,
        native_symbol=product.native_symbol,
        exchange='Dydx',
        market_type='Futures',
        kline_period=str(kline_period),
        klines=kline_group,
    )


class DydxFuturesPublicClient(pubcb.PublicClientBase):
  def __init__(self):
    self.npubc = npubc.DydxFuturesNativePublicClient()

  def query_history_kline_impl(self, product, kline_period, start_time, end_time):
    native_symbol = product.native_symbol
    start_time = start_time.replace(tzinfo=pytz.UTC) - timedelta(milliseconds=1)
    end_time = end_time.replace(tzinfo=pytz.UTC)
    update = self.npubc.get_history_kline(
        native_symbol, kline_period, start_time=start_time, end_time=end_time)
    update.msg = DydxFuturesFeedParser.parse_native_kline(update.msg, product, kline_period)
    return update

  def query_level_book_impl(self, product):
    raise NotImplementedError("Dydx futures query level book Not Implemented")


if __name__ == "__main__":
  client = DydxFuturesPublicClient()
  start_time = datetime(2022, 6, 28).replace(tzinfo=pytz.UTC)
  end_time = datetime(2022, 6, 28, 2).replace(tzinfo=pytz.UTC)
  print(client.query_history_kline(generate_product_from_str2(
      'Futures', 'Dydx', None, 'BTC-USD.PERPETUAL'), '1HOUR', start_time, end_time).msg)
